package springmvc.web.cocktails;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lombok.Data;

import org.dhbw.cocktail.Cocktail;
import org.dhbw.cocktail.mixer.ICocktailMixer;
import org.dhbw.cocktail.mixer.MixerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * Controller that handels the creation of a new Cocktail
 * 
 * @author Roland von Werden
 * 
 */
@Data
public class CreateCocktailController implements Controller {

	/**
	 * autowirde mixerfactory to access methods to create, get and search
	 * persisted Objects
	 */
	@Autowired
	@Qualifier("cocktail_mixer_factory")
	MixerFactory mixerFactory;
	ICocktailMixer mixer;

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse arg1) throws Exception {
		ModelAndView mav = new ModelAndView();
		mixer = mixerFactory.getCocktailMixer();
		// Retrieve cocktail from session-object
		HttpSession session = request.getSession();
		Cocktail cocktail = null;
		if (session.getAttribute("new_cocktail") != null
				&& session.getAttribute("new_cocktail") instanceof Cocktail
				&& request.getParameter("name") != null) {
			cocktail = (Cocktail) session.getAttribute("new_cocktail");
		} else {
			cocktail = new Cocktail();
			session.setAttribute("new_cocktail", cocktail);
		}
		// create the cocktail if the needed Parameter were sendt
		if (request.getParameter("name") != null
				&& request.getParameter("type") != null) {
			try {
				long typeId = Long.valueOf(request.getParameter("type"));
				boolean alcoholic = false;
				if (request.getParameter("alcoholic") != null)
					alcoholic = true;
				String name = request.getParameter("name");
				String desc = request.getParameter("description");
				cocktail.setName(name);
				cocktail.setAlcoholic(alcoholic);
				cocktail.setType(mixer.getCocktailTypeById(typeId));
				cocktail.setDescription(desc);
				// set a Flag if the cocktail could be saved
				if (mixer.saveCocktail(cocktail)) {
					mav.addObject("issaved", true);
					mav.addObject("cocktailId", cocktail.getId());
					mav.addObject("cocktailName", cocktail.getName());
				}
			} catch (NumberFormatException e) {
				// TODO: handle exception
			}

		}
		mav.addObject("types", mixer.getCocktailTypes());
		mav.addObject("ingredients", cocktail.getIngredientsUsed());
		mav.addObject("selectable_ingredients", mixer.getIngredients());

		return mav;
	}

}
